import datetime

from django.db import models
from django.db.models import Max

from base.models import CustomSupplier
from finance.models import CapitalAccount
from sale.models import SaleOrder, SaleReceipt
from users.models import UserInfo


class Card(models.Model):
    """优惠卡"""
    STATUS = (
        (0, '空'),
        (1, '已发放'),
    )
    code = models.CharField(verbose_name='卡号', max_length=32, blank=True, null=True)
    name = models.CharField(verbose_name='名称', max_length=32, blank=True, null=True)
    money = models.FloatField(verbose_name='面值金额', blank=True, null=True)
    remark = models.CharField(verbose_name='备注', max_length=64, blank=True, null=True)
    status = models.IntegerField(verbose_name='状态', choices=STATUS, blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.code

    class Meta:
        verbose_name = '优惠卡'
        verbose_name_plural = verbose_name
        ordering = ['-id']


class CustomerCard(models.Model):
    """客户优惠卡"""
    STATUS = (
        (0, '未消费'),
        (1, '已消费'),
    )
    CLASS = (
        (0, '赠送'),
        (1, '销售'),
        (2, '顶账'),
    )
    code = models.CharField(verbose_name='编号', max_length=32, blank=True, null=True)
    card = models.ForeignKey(Card, verbose_name='卡号', on_delete=models.CASCADE, blank=True, null=True, db_constraint=False)
    customer = models.ForeignKey(CustomSupplier, verbose_name='客户名称', on_delete=models.CASCADE, blank=True, null=True, db_constraint=False)
    sale_class = models.IntegerField(verbose_name='销售方式', choices=CLASS, blank=True, null=True)
    receipt_order_code = models.CharField(verbose_name='消费单号', max_length=32, blank=True, null=True)
    receipt_time = models.DateTimeField(verbose_name='消费时间', blank=True, null=True)
    account = models.ForeignKey(CapitalAccount, verbose_name="收款账号", blank=True, null=True, on_delete=models.RESTRICT, db_constraint=False)
    actual_money = models.FloatField(verbose_name='实售金额', blank=True, null=True)
    status = models.IntegerField(verbose_name='状态', choices=STATUS, blank=True, null=True)
    user = models.ForeignKey(UserInfo, verbose_name='操作人', blank=True, null=True, on_delete=models.CASCADE, db_constraint=False)
    remark = models.CharField(verbose_name='备注', max_length=64, blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.card.code

    class Meta:
        verbose_name = '客户优惠卡'
        verbose_name_plural = verbose_name
        ordering = ['-id']

    @classmethod
    def get_max_code(cls):
        date = datetime.datetime.now().strftime('YHK%Y%m%d')
        max_code = cls.objects.filter(code__startswith=date).aggregate(max_code=Max("code"))
        max_value = max_code['max_code']
        if max_value is None:
            num = '0001'
            code = '{0}{1}'.format(date, num)
            return code
        else:
            num = str(int(max_value[-4:]) + 1).rjust(4, '0')
            code = '{0}{1}'.format(date, num)
            return code

    def save(self, *args, **kwargs):
        if self.code == "" or self.code is None:
            self.code = self.__class__.get_max_code()

        return super().save(*args, **kwargs)
